package com.changwen.currentactivity.service;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;

import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;

import com.blankj.utilcode.util.AppUtils;
import com.changwen.currentactivity.BuildConfig;
import com.changwen.currentactivity.FloatUtils;
import com.changwen.currentactivity.R;
import com.changwen.currentactivity.accessibility.BaseAcbService;
import com.changwen.currentactivity.broadcast.NotificationClickReceiver;

import java.util.Random;

/**
 * <pre>
 *     author: lcw
 *     date  : 2022/7/13
 *     desc  : ∧_∧
 * </pre>
 */
public class AccessService extends BaseAcbService {

    private final String TAG = "AccessService";
    private final Boolean LOG = BuildConfig.DEBUG;

    @Override
    protected void onServiceConnected() {
        super.onServiceConnected();
        if (LOG)
            Log.e(TAG, "onServiceConnected");
    }

    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        super.onAccessibilityEvent(event);
        //注意这个方法回调，是在主线程，不要在这里执行耗时操作
        if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {

            String packageName = event.getPackageName().toString();
            String className = event.getClassName().toString();
            ComponentName componentName = new ComponentName(packageName, className);

            ActivityInfo activityInfo = tryGetActivity(componentName);
            boolean isActivity = activityInfo != null;
            if (isActivity) {
                String appName = AppUtils.getAppName(packageName);
                String title = String.format("%s（%s）", appName, packageName);
//                updateForegroundNotification(title, className);

                FloatUtils.showFloat(this, FloatUtils.floatTag, title, className);
                if (LOG)
                    Log.i(TAG, "appName = " + appName + "  " + "packageName = " + packageName + "  " + "className = " + className);
            }
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        if (LOG)
            Log.e(TAG, "onCreate");
//        setForegroundNotification("Activity记录", "");
    }

    @Override
    public void onInterrupt() {
        super.onInterrupt();
        if (LOG)
            Log.e(TAG, "onInterrupt");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (LOG)
            Log.e(TAG, "onDestroy");
    }

    private ActivityInfo tryGetActivity(ComponentName componentName) {
        try {
            return getPackageManager().getActivityInfo(componentName, 0);
        } catch (PackageManager.NameNotFoundException e) {
            return null;
        }
    }

    private void setForegroundNotification(String title, String text) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            setForegroundService(title, text);
        }
    }

    private void updateForegroundNotification(String title, String text) {
        if (mBuilder != null) {
            Notification notification = mBuilder
                    .setContentTitle(title)
                    .setContentText(text)
                    .build();
            mNotificationManager.notify(NOTIFICATION_ID, notification);
            startForeground(NOTIFICATION_ID, notification);
        }
    }

    private NotificationManager mNotificationManager;
    private NotificationCompat.Builder mBuilder;
    private int NOTIFICATION_ID;

    /**
     * 通过通知启动服务
     */
    @SuppressLint("UnspecifiedImmutableFlag")
    @RequiresApi(api = Build.VERSION_CODES.N)
    public void setForegroundService(String title, String text) {
        NOTIFICATION_ID = new Random().nextInt(Integer.MAX_VALUE);
        String CHANNEL_ID = getResources().getString(R.string.notification_channel_id);
        String CHANNEL_NAME = getResources().getString(R.string.notification_channel_name);
        int IMPORTANCE_LEVEL = NotificationManager.IMPORTANCE_LOW;

        mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, IMPORTANCE_LEVEL);
            mNotificationManager.createNotificationChannel(channel);
        }

        Intent intent = new Intent(this, NotificationClickReceiver.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            pendingIntent = PendingIntent.getBroadcast(this, NOTIFICATION_ID, intent, PendingIntent.FLAG_IMMUTABLE);
        } else {
            pendingIntent = PendingIntent.getBroadcast(this, NOTIFICATION_ID, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        }

        mBuilder = new NotificationCompat.Builder(this, CHANNEL_ID);
        Notification notification = mBuilder
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(title)
                .setContentText(text)
                .setAutoCancel(true)
                .setCategory(Notification.CATEGORY_SERVICE)
                .setOngoing(true)
                .setPriority(IMPORTANCE_LEVEL)
                .setContentIntent(pendingIntent)
                .build();
        startForeground(NOTIFICATION_ID, notification);
    }

}
